import React from 'react'
import style from './tabs.scss'
import { mergeStyle } from './mergeStyle'

export const Tabs = ({ name, activeCode, items, getItemValue, renderTitle, renderContent, onActiveTab }) => {
    const wrapOnActiveTab = React.useCallback(ev => {
        const currentCode = ev.target.dataset.value
        if (activeCode !== currentCode) {
            onActiveTab(currentCode)
        }
    }, [activeCode])

    const header = <div className={style.header}>
        {items.map(item => {
            const value = getItemValue(item)
            const title = renderTitle(item)
            const active = activeCode === value

            return <React.Fragment key={value}>
                <input type='radio' id={value} name={name} className={mergeStyle(style, 'tab')}
                    data-value={value} checked={active ? true : false} onChange={wrapOnActiveTab} />
                <label htmlFor={value}>{title}</label>
            </React.Fragment>
        })}
    </div>

    const content = items.map(item => {
        const value = getItemValue(item)
        const active = activeCode === value

        return active ? (
            <div key={getItemValue(item)} className={mergeStyle(style, 'tab__content')}>
                {renderContent(item)}
            </div>) : <div key={getItemValue(item)} />
    })

    return (
        <div className={style['tab-wrap']}>
            {header}
            {content}
        </div>
    )
}